package org.example.mydeom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.example.mydeom.common.BaseContext;
import org.example.mydeom.common.MessageConstant;
import org.example.mydeom.exception.IdIllegalException;
import org.example.mydeom.exception.RoleHasFoundException;
import org.example.mydeom.exception.RoleNotFoundException;
import org.example.mydeom.mapper.RoleMapper;
import org.example.mydeom.pojo.dto.RoleForUserDTO;
import org.example.mydeom.pojo.entity.Role;
import org.example.mydeom.pojo.entity.UserRole;
import org.example.mydeom.result.Result;
import org.example.mydeom.service.RoleService;
import org.example.mydeom.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public Result<Void> add(Role role) {
        Role one=roleMapper.getByName(role.getRoleName());
        if(one != null){
            if(one.getDeleted()==0){
                throw new RoleHasFoundException(MessageConstant.ROLE_HAS_FOUND);//角色已存在
            }else {
                one.setUpdateBy(BaseContext.getCurrentId());
                one.setDeleted(0);
                one.setUpdateTime(LocalDateTime.now());
                roleMapper.MyUpdateById(one);
                return Result.success();
            }
        }
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        role.setCreateBy(BaseContext.getCurrentId());
        role.setUpdateBy(BaseContext.getCurrentId());
        save(role);
        return Result.success();
    }

    @Override
    public Result<Void> addRoleForUser(RoleForUserDTO roleForUser) {
        List<UserRole> userRoles = new ArrayList<>();
        //判断角色是否存在
        //int count= roleMapper.selDel(roleForUser.getId());
        Long count = roleMapper.selectCount(new LambdaQueryWrapper<Role>().eq(Role::getId, roleForUser.getId()));
        if(count==0){
            throw new RoleNotFoundException(MessageConstant.ROLE_NOT_FOUND);//角色不存在
        }
        for (Long userId : roleForUser.getUserIds()) {
            UserRole one = userRoleService.lambdaQuery()
                    .eq(UserRole::getUserId, userId)
                    .eq(UserRole::getRoleId, roleForUser.getId())
                    .one();
            if(one!=null){
                continue;
            }
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleForUser.getId());
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setCreateBy(BaseContext.getCurrentId());
            userRoles.add(userRole);
        }
        boolean b = userRoleService.saveBatch(userRoles);
        if(b){
            return  Result.success();
        }else{
            return Result.error("添加失败");
        }
    }
    @Override
    @Transactional
    public void delById(Long id) {
        if(id==null||id<=0){
            throw new IdIllegalException(MessageConstant.ID_ILLEGAL);//id不合法
        }
        //删除角色
        lambdaUpdate()
                .eq(Role::getId, id)
                .set(Role::getDeleted, 1)
                .set(Role::getUpdateTime, LocalDateTime.now())
                .set(Role::getUpdateBy, BaseContext.getCurrentId())
                .update();
        //删除用户角色关系
        userRoleService
                .lambdaUpdate()
                .eq(UserRole::getRoleId, id)
                .set(UserRole::getDeleted, 1);
//        userRoleService.remove(new QueryWrapper<UserRole>()
//                .eq("role_id", id));
    }

    @Override
    public Result<Role> findById(Long id) {
        if(id==null||id<=0){
            throw new IdIllegalException(MessageConstant.ID_ILLEGAL);//id不合法
        }
        Role role = getById(id);
        if (role == null){
            throw new RoleNotFoundException(MessageConstant.ROLE_NOT_FOUND);//角色不存在
        }
        return Result.success(role);
    }
}
